package finalVersion;

import java.io.*;
import java.net.*;

public class Connection implements Runnable {

	ServerGUI server = null;
	private Socket communicationSocket = null;
	private OutputStreamWriter out = null;
	private BufferedReader in = null;
	private int listeningPortOfClient;
	private String userID;
	private String hostAddr;

	public Connection(ServerGUI server, Socket s) {
		this.server = server;
		this.communicationSocket = s;
	}

	public void closeConnectionSocket() {
		try {
			if (in != null) {
				in.close();
			}
			if (out != null) {
				out.close();
			}
			communicationSocket.close();
		} catch (Exception e) {

		}
	}

	public void sendMessage(String message) {
		try {
			out.write(message + "\n");
			out.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void run() {
		OutputStream socketOutput = null;
		InputStream socketInput = null;

		try {
			socketOutput = communicationSocket.getOutputStream();
			out = new OutputStreamWriter(socketOutput);
			socketInput = communicationSocket.getInputStream();
			in = new BufferedReader(new InputStreamReader(socketInput));
			String input = null;

			// parse the string according to protocol to unserstand request that
			// user send to server
			while ((input = in.readLine()) != null) {
				if (input.startsWith("Connect:")) {
					String[] detail = input.substring(8).split(":");
					userID = detail[0];
					listeningPortOfClient = Integer.parseInt(detail[1]);
					hostAddr = detail[2];
					this.server.addUser(userID, this);
					server.setDetailConnection(userID + " Connect from "
							+ communicationSocket.getInetAddress()
							+ " From Port " + communicationSocket.getPort());

				} else if (input.startsWith("Text")) {
					this.server.sendToAllClients(input);
				} else if (input.startsWith("Disconnect")) {
					System.out.println(input);

					// close socket and stream
					String disconnect = "Disconnect:" + userID;
					server.setDetailConnection(userID + " Disconnect");
					server.sendToAllClients(disconnect);
					server.closeConnection(this, userID);

				} else if (input.startsWith("ChatWith:")) {
					System.out.println(input);
					Connection c = server.userIDtoConnection.get(input
							.substring(9));
					String chatprivate = "ChatPrivate:" + c.hostAddr + ":"
							+ c.listeningPortOfClient + ":" + c.userID;
					System.out.println(chatprivate);
					this.sendMessage(chatprivate);

				} else {

				}
			}
		} catch (Exception e) {
			e.printStackTrace(System.err);
		}finally {
			try {
				if (in != null)
					in.close();
				if (out != null)
					out.close();
				communicationSocket.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		server.closeConnection(this, userID);
	}
}
